package com.jf.map;

import java.util.ArrayList;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.jf.demo.MyAlreadyOrder;
import com.jf.demo.R;
import com.jf.map.NearbyUser.MyLocationListenner;
import com.jf.map.NearbyUser.MyOverlay;
import com.jf.map.NearbyUser.locationOverlay;
import com.sys.android.util.FinalUntil;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class MyOrderMap extends Activity {
	
	private int[] messImage = FinalUntil.messImage; 
	
	MyOverlay mOverlay = null;
	
	private ArrayList<OverlayItem> mItems = null;
	// 定位相关
	LocationClient mLocClient;
	LocationData locData = null;
	public MyLocationListenner myListener = new MyLocationListenner();
	
	//定位图层
	locationOverlay myLocationOverlay = null;
	//弹出泡泡图层
	private PopupOverlay   pop  = null;//弹出泡泡图层，浏览节点时使用
	public TextView  popupText = null;//泡泡view
	private View viewCache = null;
	private View popupInfo = null;
	
	private View popupLeftImage = null;

	private TextView popupRightImage = null;
	
	//地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
	//如果不处理touch事件，则无需继承，直接使用MapView即可
	MapView mMapView = null;	// 地图View
	private MapController mMapController = null;

	//UI相关
	OnCheckedChangeListener radioButtonListener = null;
	Button requestLocButton = null;
	boolean isRequest = false;//是否手动触发请求定位
	boolean isFirstLoc = true;//是否首次定位
	public BMapManager mBMapMan;
	
	
	public TextView nearbyUserName;
	
	private Double mapY;
	private Double mapX;
	
	private String courName;
	private int brandImag;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mBMapMan=new BMapManager(getApplication());  
		mBMapMan.init(null); 

		setContentView(R.layout.my_order_map);
		
		Intent intent = getIntent();
		mapX = intent.getDoubleExtra("mapX", 0.0);
		mapY = intent.getDoubleExtra("mapY", 0.0);
		courName = intent.getStringExtra("courName");
		brandImag = intent.getIntExtra("brandImag", 0);
		
		
		CharSequence titleLable="定位功能";
        setTitle(titleLable);
        
        
		mMapView = (MapView)findViewById(R.id.orderMapsView);//获取地图控件
		
		mMapController = mMapView.getController();
        mMapView.getController().setZoom(18);
        mMapView.getController().enableClick(true);
        mMapView.setBuiltInZoomControls(true);
     
        
        //定位初始化
        mLocClient = new LocationClient( this );
        locData = new LocationData();
        mLocClient.registerLocationListener( myListener );
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);//打开gps
        option.setCoorType("bd09ll");     //设置坐标类型
        option.disableCache(false);
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
       
        //定位图层初始化
		myLocationOverlay = new locationOverlay(mMapView);
		//设置定位数据
	    myLocationOverlay.setData(locData);
	    //添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		//修改定位数据后刷新图层生效
		mMapView.refresh();
	}
	/**
	 * 创建弹出泡泡图层
	 */
	public void createPaopao(){
		/**
         * 向地图添加自定义View.
         */
        viewCache = getLayoutInflater().inflate(R.layout.custom_text_view, null);
        popupInfo = (View) viewCache.findViewById(R.id.popinfo);
        popupLeftImage = (View) viewCache.findViewById(R.id.popleftImage);
//        popupLeft = (View) viewCache.findViewById(R.id.popleft);
//        popupRight = (View) viewCache.findViewById(R.id.popright);
        popupText =(TextView) viewCache.findViewById(R.id.textcache);
        popupRightImage = (TextView) viewCache.findViewById(R.id.mapImage);
        /**
         *	弹出的气泡中点击事件的监听
         */
        PopupClickListener popListener = new PopupClickListener(){
			@Override
			public void onClickedPopup(int index) {
				
				if ( index == 0){
					//更新item位置菜单按钮中的点击事件 
				     
				}
				else if(index == 2){
					//更新图标
					
				}
			}
         };
        pop = new PopupOverlay(mMapView,popListener);
//        MyLocationMapView.pop = pop;
	}
	/**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
    	
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return ;
            
            locData.latitude = location.getLatitude();
            locData.longitude = location.getLongitude();
            //如果不显示定位精度圈，将accuracy赋值为0即可
            locData.accuracy = location.getRadius();
            // 此处可以设置 locData的方向信息, 如果定位 SDK 未返回方向信息，用户可以自己实现罗盘功能添加方向信息。
            locData.direction = location.getDerect();
            //更新定位数据
            myLocationOverlay.setData(locData);
            //更新图层数据执行刷新后生效
//            mMapView.refresh();
            //是手动触发请求或首次定位时，移动到定位点
            if (isRequest || isFirstLoc){
            	//移动地图到定位点
            	Log.d("LocationOverlay", "receive location, animate to it");
                mMapController.animateTo(new GeoPoint((int)(locData.latitude* 1e6), (int)(locData.longitude *  1e6)));
                isRequest = false;
                myLocationOverlay.setLocationMode(LocationMode.FOLLOWING);
                Log.d("LocationOverlay", locData.latitude+"-"+locData.longitude);
                GraphicsOverlay graphicsOverlay = new GraphicsOverlay(mMapView);
				mMapView.getOverlays().add(graphicsOverlay);
				

				double mLat2 =mapY;
				double mLon2 =mapX;

				// 用给定的经纬度构造GeoPoint，单位是微度 (度 * 1E6)
				
				GeoPoint p2 = new GeoPoint((int) (mLat2 * 1E6), (int) (mLon2 * 1E6));

				// 准备overlay图像数据，根据实情情况修复
				Drawable mark = getResources().getDrawable(R.drawable.icon_gcoding);
				// 用OverlayItem准备Overlay数据 

				
				// 使用setMarker()方法设置overlay图片,如果不设置则使用构建ItemizedOverlay时的默认设置
				OverlayItem item2 = new OverlayItem(p2, "快递员："+courName, "item2");
				item2.setMarker(mark);
				

				/**
				 * 创建自定义overlay
				 */
				Drawable pic = getResources().getDrawable(R.drawable.icon_gcoding);
				mOverlay = new MyOverlay(pic, mMapView);
				// 现在所有准备工作已准备好，使用以下方法管理overlay.
				// 添加overlay, 当批量添加Overlay时使用addItem(List<OverlayItem>)效率更高

				mOverlay.addItem(item2);

				mItems = new ArrayList<OverlayItem>();
				mItems.addAll(mOverlay.getAllItem());
				mMapView.getOverlays().add(mOverlay);
				mMapView.refresh();
				 //创建 弹出泡泡图层
		        createPaopao();				
				
            }
            //首次定位完成
            isFirstLoc = false;
        }
        
        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null){
                return ;
            }
        }
    }
    
    //继承MyLocationOverlay重写dispatchTap实现点击处理
  	public class locationOverlay extends MyLocationOverlay{

  		public locationOverlay(MapView mapView) {
  			super(mapView);
  			// TODO Auto-generated constructor stub
  		}
  		/**
  		 * 点击自已位置的图标时显示气泡
  		 */
  		@Override
  		protected boolean dispatchTap() {
  			// TODO Auto-generated method stub
  			//处理点击事件,弹出泡泡
//  			popupText.setBackgroundResource(R.drawable.popup);
			popupText.setText("我的位置");
			pop.showPopup(BMapUtil.getBitmapFromView(popupText),
					new GeoPoint((int)(locData.latitude*1e6), (int)(locData.longitude*1e6)),
					8);
  			return true;
  		}
  		
  	}
  	public class MyOverlay extends ItemizedOverlay {

		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}
		/**
		 *点击地图上气泡时候触发 
		 */
		@Override
		public boolean onTap(int index) {
			OverlayItem item = getItem(index);
			
			popupText.setText(getItem(index).getTitle());
			popupRightImage.setBackgroundResource(messImage[brandImag]);
			Bitmap[] bitMaps={
			    BMapUtil.getBitmapFromView(popupLeftImage), 		
			    BMapUtil.getBitmapFromView(popupInfo), 		
//			    BMapUtil.getBitmapFromView(popupRight)
		    };
		    pop.showPopup(bitMaps,item.getPoint(),32);
			return true;
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mMapView) {
			if (pop != null) {
				pop.hidePop();
//				mMapView.removeView(button);
			}
			return false;
		}

	}
    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
    	//退出时销毁定位
        if (mLocClient != null)
            mLocClient.stop();
        mMapView.destroy();
        super.onDestroy();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	mMapView.onSaveInstanceState(outState);
    	
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	mMapView.onRestoreInstanceState(savedInstanceState);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public void finishMyOrder(View v){
    	this.finish();
    }
}
